<template>
  <div class="share-group">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>群组列表</span>
            <el-button 
              v-if="showBack" 
              type="text" 
              size="small" 
              style="float: right;margin-top: -8px;"
              @click="$emit('toggleShowGroup')">返回人员选择</el-button>
          </div>
        <div class="btngroup">
          <el-button
            class="filter-item"
            size="small"
            icon="el-icon-plus"
            @click="
              () => {
                dialogShareVisible = true;
                actionType = '新建';
              }
            "
            >新增
          </el-button>
        </div>
        <div class="group-table">
          <el-table
            ref="userTable"
            :data="dataSource"
            v-loading="loading"
            size="small"
            stripe
            style="text-align: center"
            @selection-change="rows => $emit('selectGroup', rows)"
          >
            <el-table-column v-if="showSelection" type="selection" width="44"></el-table-column>
            <el-table-column type="index" label="#" width="40"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="
                    () => {
                      dialogShareVisible = true;
                      actionType = '编辑';
                      rowData = scope.row;
                      groupName = scope.row.name;
                    }
                  "
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleClickUserInfo(scope.row, 'userInfo')"
                  >用户详情</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="handleClickUserInfo(scope.row, 'auth')"
                  >授权</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="
                    () => {
                      rowData = scope.row;
                      showDeleteConfirm();
                    }
                  "
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card" v-loading="loading">
          <div slot="header" class="clearfix">
            <span>{{usersCardTitle}}人员列表</span>
          </div>
        <div style="margin-bottom: 6px" v-if="rowData">【{{ rowData.name}}】{{usersCardTitle}}所有的人({{groupUsers.length}}人)</div>
        <div class="user-list" v-if="rowData">
          <draggable v-model="groupUsers" ghostClass="ghost" chosenClass="chosen" @end="handleDragUser">
              <transition-group>
                <el-tag
                  :key="index"
                  v-for="(item, index) in groupUsers"
                  size="small"
                  style="margin-bottom: 4px; cursor: pointer;"
                  closable
                  :disable-transitions="false"
                  @close="removeUser(item)"
                >
                  {{ item.first_name }}
                </el-tag>
              </transition-group>
          </draggable>
          <el-button
            size="mini"
            icon="el-icon-plus"
            @click="dialogUsersVisible = true"
            >加入</el-button
          >
          <el-button
            v-if="showUsersType === 'userInfo'"
            size="mini"
            icon="el-icon-refresh-left"
            @click="handleUpdateGroupSort"
            >排序刷新</el-button
          >
        </div>
        <div v-else class="no-select-group">请先选择群组，查看用户详情</div>

        <div class="pending-remove" v-if="penddingDeleteUsers.length">
          <div class="title">待移除人员</div>
          <div class="user-list">
            <el-tag
              :key="index"
              size="small"
              style="margin-bottom: 4px"
              v-for="(item, index) in penddingDeleteUsers"
              closable
              :disable-transitions="false"
              @close="backUser(item)"
            >
              {{ item.first_name }}
            </el-tag>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleRemoveUser"
            >移除</el-button
          >
          </div>
        </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 分享人员选择对话框 -->
    <el-dialog
      :title="`${actionType}群组`"
      width="360px"
      :close-on-click-modal="false"
      :visible.sync="dialogShareVisible"
      append-to-body
    >
      <el-form :inline="true" label-width="80px">
        <el-form-item label="群组名称">
          <el-input
            placeholder="请输入"
            v-model="groupName"
            clearable
            style="width: 230px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="small" @click="dialogShareVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" size="small" @click="handleUpdateShareToGroup"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 群组人员选择对话框 -->
    <el-dialog
      :title="`选择人员`"
      width="70%"
      :close-on-click-modal="false"
      :visible.sync="dialogUsersVisible"
      append-to-body
    >
      <user-manager ref="userManager" :userOuter="false" :shareGroup="false" :onSelectUsers="handleSelectShareUser"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  getShareGroupList,
  createShareGroup,
  updateShareGroup,
  deleteShareGroup,
  patchUpdateUser,
  updateGroupOrderSort
} from "@/api/user.js";
import user from "../../../../store/modules/user";

import { mapGetters } from "vuex";

// 导入draggable组件
import draggable from 'vuedraggable'
export default {
  name: "ShareGroup",
  props: {
    showSelection: {
      type: Boolean,
      default: true
    },
    showBack: {
      type: Boolean,
      default: true
    }
  },
  components: {
    UserManager: () =>
      import("@/views/markSys/taskCenter/components/userManager"),
    draggable
  },
  computed: {
    usersCardTitle() {
      return this.showUsersType === 'userInfo' ? '群组' : '授权'
    }
  },
  data() {
    return {
      loading: false,
      dialogShareVisible: false, // 是否显示群组编辑对话框
      dialogUsersVisible: false, // 是否显示人员选择对话框
      dataSource: [],
      showUsersType: 'userInfo',
      groupName: "", // 群组名称值
      actionType: "新建",
      rowData: null, // 选中表格行数据
      groupUsers: [], // 群组人员列表
      penddingDeleteUsers: [], // 待删除人员列表
    };
  },
  created() {
    this.fetchShareGroupList();
  },
  methods: {
    clearActionData() {
      this.rowData = null
      this.groupUsers = []
      this.penddingDeleteUsers = []
    },
    /**
     * 处理点击用户详情
     * type: 用户详情、授权
     */
    handleClickUserInfo(row, type) {
      const { userinfo, views_userinfo } = row
      this.showUsersType = type
      this.rowData = row
      this.groupUsers = type === 'userInfo' ? [...userinfo] : [...views_userinfo]
      this.penddingDeleteUsers = []
    },
    /**
     * 请求群组表格数据
     */
    async fetchShareGroupList() {
      this.loading = true
      const { data } = await getShareGroupList();
      this.dataSource = data;
      this.loading = false
    },
    /**
     * 发送新建、修改群组名称请求
     */
    async handleUpdateShareToGroup() {
      if (!this.groupName) {
        this.$message.warning("请输入群组名称");
        return;
      }
      const hide = this.$message.info("正在提交");
      let result = null;
      if (this.actionType === "新建") {
        result = await createShareGroup({ name: this.groupName, user: [] });
      } else {
        result = await updateShareGroup(this.rowData.id, {
          name: this.groupName,
        });
      }
      if (result) {
        hide.close();
        this.$message.success(`${this.actionType}群组成功`);
      } else {
        this.$message.success(`${this.actionType}群组失败`);
      }
      this.dialogShareVisible = false;
      this.fetchShareGroupList();
    },
    /**
     * 删除群组确认框
     */
    showDeleteConfirm() {
      this.$confirm("确认删除此群组吗？").then((res) => {
        this.handleDeleteGroup();
      });
    },
    /**
     * 发送删除群组数据请求
     */
    async handleDeleteGroup() {
      const hide = this.$message.info("正在提交");
      const result = await deleteShareGroup(this.rowData.id);
      if (result) {
        hide.close();
        this.$message.success(`删除群组成功`);
        this.clearActionData()
      }
      this.fetchShareGroupList();
    },
    /**
     * 将群组人员移出，待删除列表增加
     */
    removeUser(user) {
      const index = this.groupUsers.findIndex((item) => item.id === user.id);
      this.groupUsers.splice(index, 1);
      this.penddingDeleteUsers.push(user);
    },
    /**
     * 将待删除列表移出，群组人员列表增加
     */
    backUser(user) {
      const index = this.penddingDeleteUsers.findIndex(
        (item) => item.id === user.id
      );
      this.penddingDeleteUsers.splice(index, 1);
      this.groupUsers.push(user);
    },
      //拖拽结束事件
    async handleDragUser(e) {
      // if(this.groupUsers.length === 1) return
      // const {newIndex} = e
      // const moveUser = this.groupUsers[newIndex]
      // if(newIndex === 0) {
      //   const {order} = this.groupUsers[newIndex + 1]
      //   moveUser.order = order + 1
      // } else{
      //   const {order}= this.groupUsers[newIndex - 1]
      //   moveUser.order = order - 1
      //   // if(order !== 0) {
      //   // } else {
      //   //   moveUser.order = 0
      //   // }
      // }
      // const {id, order} = moveUser
      // await patchUpdateUser(id, { order })
    },
    /**
     * 发送移除群组人员请求
     */
    async handleRemoveUser() {
      this.$confirm("确认移除所选的人员吗？").then(async (res) => {
        const { id, userinfo } = this.rowData;
        const hide = this.$message.info("正在提交");
        const userIds = this.groupUsers.map((item) => item.id);
        const param = {}
        if(this.showUsersType === 'userInfo') {
          param.user = userIds
        } else {
          param.views_user = userIds
        }
        const result = await updateShareGroup(this.rowData.id, param);
        if (result) {
          hide.close();
          this.$message.success(`移除人员成功`);
        }
        this.penddingDeleteUsers = [];
        this.fetchShareGroupList();
      });
    },
    /**
     * 获取选择人员列表，更新群组人员信息
     */
    async handleSelectShareUser(selectedUsers) {
      const uniqueUsers = this.uniqueArray([
        ...this.groupUsers,
        ...selectedUsers,
      ]);
      const userIds = uniqueUsers.map((item) => item.id);
      const param = {}
      if(this.showUsersType === 'userInfo') {
        param.user = userIds
      } else {
        param.views_user = userIds
      }
      const result = await updateShareGroup(this.rowData.id, param);
      if (result) {
          this.$message.success(`添加人员成功`);
        }
      this.groupUsers = uniqueUsers;
      this.penddingDeleteUsers = []
      this.$refs.userManager.clearSelect()
      this.dialogUsersVisible = false;
      this.fetchShareGroupList();
    },
    async handleUpdateGroupSort() {
      this.loading = true
      const ids = this.groupUsers.map(item => item.id)
      await updateGroupOrderSort(this.rowData.id, {user_info: ids.toString()})
      this.loading = false
      // 更新用户order
      const { data } = await getShareGroupList();
      this.dataSource = data
      const { userinfo} = data.find(item => item.id === this.rowData.id) || {}
      this.groupUsers = userinfo || []
    },
    uniqueArray(list = []) {
      let res = list.filter(function (item, index, self) {
        return self.findIndex((el) => el.id == item.id) === index;
      });
      return res;
    },
  }
};
</script>
<style lang="scss">
.share-group {
  margin: 20px 0 0;
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .no-select-group {
    text-align: center;
    padding: 24px 0;
  }
  .user-list {
    border: 1px solid #eee;
    padding: 8px;
    .chosen{
      background-color: red !important;
      color: #fff;
    }
    .ghost{
      background-color: red !important;
    }
  }
  .pending-remove {
    margin-top: 10px;

    .title,
    .users {
      margin-bottom: 6px;
    }
  }
}
</style>